using System;
using FubuMVC.Core.Util;

namespace FubuMVC.Core.Runtime
{
    public interface IModelState
    {
        void ProvideModel<TModel>(TModel model);
        TModel RetrieveModel<TModel>();
    }

    public class ModelState : IModelState
    {
        private readonly Cache<Type, object> _modelState = new Cache<Type, object>();

        public void ProvideModel<TModel>(TModel model)
        {
            _modelState.Store(typeof (TModel), model);
        }

        public TModel RetrieveModel<TModel>()
        {
            var modelType = typeof (TModel);

            if( ! _modelState.Has(modelType))
            {
                throw new ApplicationException("A request was made for a model of type '{0}' but no model was provided for this request"
                    .ToFormat(modelType.Name));
            }

            return (TModel) _modelState.Retrieve(typeof (TModel));
        }
    }
}